//
//  LoginViewController.swift
//  Box
//
//  Created by mn on 2025/3/31.
//
import UIKit
class LoginViewController: BaseViewController{

    var complete:( () -> Void)?
    let inputPhoneView = InputPhoneView()
    let agreementView = AgreementView()
    let sendCodeView = SendCodeView()
    lazy var button: InsetBorderButton = {
        let button = InsetBorderButton(type: .custom)
        button.setTitle("同意协议并登录", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.layer.cornerRadius = 7.5
        button.titleLabel?.font = .systemFont(ofSize: 16)
        button.backgroundColor = .fromHex("#B3F832")
        button.addAction { [weak self] in
            self?.check()
        }
        return button
    }()
    // 手机号正则校验
    func isValidPhone(_ phone: String) -> Bool {
        let pattern = "^1\\d{10}$"  // 以 1 开头的 11 位数字
        let regex = try? NSRegularExpression(pattern: pattern)
        let range = NSRange(location: 0, length: phone.utf16.count)
        return regex?.firstMatch(in: phone, options: [], range: range) != nil
    }
    func check() {
        if !agreementView.agreeButton.isSelected {
            toast("请先同意协议")
            return
        }
        guard let phone = inputPhoneView.phoneTextField.text,isValidPhone(phone)
        else {
            toast("请输入正确的手机号")
            return
        }
        if inputPhoneView.isHidden{
            guard let code = sendCodeView.getInputCode() else {
                toast("请输入正确的验证码")
                return
            }
            login(phone, code: code)
        }else{
            getCode(phone)
        }
    }
    func login(_ phone: String, code: String) {
        APIService.request(api: .login(phone: phone, code: code)) { [weak self] (result,res) in
            if result.success{
                self?.complete?()
                UserManager.shared.updateUser(from: res)
                self?.toast("登录成功")
                self?.navigationController?.pop()
            }
        }
    }
    func getCode(_ phone: String) {
        APIService.request(api: .getCode(phone: phone)) {
            [weak self] (result,_) in
            if result.success {
                self?.inputPhoneView.isHidden = true
                self?.sendCodeView.phone = phone
                self?.sendCodeView.isHidden = false
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        updateNav()
        view.backgroundColor = .init(hex: "#151515")
        view.addSubview(inputPhoneView)
        inputPhoneView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom).offset(92)
            make.left.right.equalToSuperview()
            make.height.equalTo(200)
        }
        sendCodeView.isHidden = true
        view.addSubview(sendCodeView)
        sendCodeView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom).offset(92)
            make.left.right.equalToSuperview()
            make.height.equalTo(200)
        }
        view.addSubview(button)
        button.snp.makeConstraints { make in
            make.top.equalTo(inputPhoneView.snp.bottom).offset(48)
            make.left.right.equalToSuperview().inset(50)
            make.height.equalTo(48)
        }
        view.addSubview(agreementView)
        agreementView.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20)
            make.left.right.equalToSuperview().inset(20)
        }
#if DEBUG
        agreementView.agreeButton.isSelected = true
#endif
    }
    func updateNav()  {
        nav.backButton.setImage(UIImage.arrowLeftGreen, for: .normal)
        nav.backButton.backgroundColor = .white.withAlphaComponent(0.1)
        nav.addRightButton()
        nav.rightButton.addAction {
            [weak self] in
            self?.navigationController?.pop()
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        inputPhoneView.phoneTextField.resignFirstResponder()
    }
}
